package com.mars.diancan.controller;

import com.lly835.bestpay.model.PayResponse;
import com.lly835.bestpay.rest.type.Post;
import com.mars.diancan.common.ResultEnum;
import com.mars.diancan.dto.OrderDTO;
import com.mars.diancan.exception.DiancanException;
import com.mars.diancan.pojo.OrderMaster;
import com.mars.diancan.service.OrderService;
import com.mars.diancan.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * 支付模块：
 * 1、pom.xml中引入支付sdk依赖，引入freemarker依赖
 * 2、create方法，返回ModelAndView的freemarker模板，
 *    在template文件夹下创建 pay/create.ftl （freemarker默认后缀名.ftl）
 * @author MARS
 * @date 2018/6/28
 */
@Controller
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private PayService payService;


    /**
     * 使用freemarker模板 返回支付页面
     * @param orderId 订单id号
     * @param returnUrl 返回url
     */
    @GetMapping("/create")
    public ModelAndView create(@RequestParam("orderId") String orderId,
                               @RequestParam("returnUrl") String returnUrl,
                               Map<String,Object> map) {
        // 查询订单
        OrderDTO orderDTO = orderService.findOne(orderId);
        if (orderDTO == null) {
            throw new DiancanException(ResultEnum.ORDER_NOT_EXIST);
        }

        // 发起支付
        PayResponse payResponse = payService.create(orderDTO);
        // 将参数注入模板中
        map.put("payResponse",payResponse);
        map.put("returnUrl",returnUrl);
        return new ModelAndView("pay/create",map);


    }

    /**
     * 接收微信后端的异步通知,
     * 需要与application.yml中配置的notifyUrl请求地址保持一致
     */
    @PostMapping("/notify")
    public ModelAndView notify(@RequestBody String notifyData) {
        payService.notify(notifyData);

        // 返回给微信处理结果
        return new ModelAndView("pay/success");
    }
}
